// SettingsScreen.kt
package com.example.nutritionmanager.profile

import android.app.Activity
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.example.nutritionmanager.R
import com.example.nutritionmanager.buttons.PrimaryButton
import com.example.nutritionmanager.viewModels.SettingsViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
    viewModel: SettingsViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    val context = LocalContext.current
    val activity = remember { context as? Activity }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("设置", color = Color.White) },
                navigationIcon = {
                    IconButton(onClick = { activity?.finish() }) {
                        Icon(
                            imageVector = Icons.Filled.ArrowBack,
                            contentDescription = "返回",
                            tint = Color.White
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
                .padding(padding)
                .verticalScroll(rememberScrollState())
        ) {
            // 通用设置卡片
            SettingsCard(title = "通用设置") {
                SettingItem(
                    title = "深色模式",
                    iconRes = R.drawable.dark_mode,
                    action = {
                        Switch(
                            checked = uiState.isDarkMode,
                            onCheckedChange = { viewModel.toggleDarkMode(it) }
                        )
                    }
                )
                Divider(color = Color.LightGray, thickness = 1.dp)
                SettingItem(
                    title = "消息通知",
                    iconRes = R.drawable.notification,
                    action = {
                        Switch(
                            checked = uiState.notificationsEnabled,
                            onCheckedChange = { viewModel.toggleNotifications(it) }
                        )
                    }
                )
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 账号安全卡片
            SettingsCard(title = "账号与安全") {
                SettingItem(
                    title = "修改密码",
                    iconRes = R.drawable.password_update,
                    onClick = { /* 跳转修改密码界面 */ }
                )
                Divider(color = Color.LightGray, thickness = 1.dp)
                SettingItem(
                    title = "绑定邮箱",
                    iconRes = R.drawable.email,
                    subtitle = uiState.boundEmail.ifEmpty { "未绑定" },
                    onClick = { /* 跳转邮箱绑定界面 */ }
                )
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 数据管理卡片
            SettingsCard(title = "数据管理") {
                SettingItem(
                    title = "清除缓存",
                    iconRes = R.drawable.cache_clear,
                    subtitle = "${uiState.cacheSize} MB",
                    onClick = { viewModel.clearCache() }
                )
            }

            Spacer(modifier = Modifier.height(24.dp))

            PrimaryButton(
                onClick = { viewModel.restoreDefaults() },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
                text = "恢复默认设置"
            )
        }
    }
}

// 设置项通用组件
@Composable
private fun SettingItem(
    title: String,
    iconRes: Int,
    subtitle: String = "",
    onClick: (() -> Unit)? = null,
    action: @Composable (() -> Unit)? = null
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 12.dp, horizontal = 16.dp)
            .let { if (onClick != null) it.clickable { onClick() } else it },
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Icon(
                painter = painterResource(id = iconRes),
                contentDescription = null,
                tint = MaterialTheme.colorScheme.primary,
                modifier = Modifier.size(24.dp)
            )
            Spacer(modifier = Modifier.width(16.dp))
            Column {
                Text(
                    text = title,
                    fontSize = 16.sp,
                    color = MaterialTheme.colorScheme.onSurface
                )
                if (subtitle.isNotEmpty()) {
                    Text(
                        text = subtitle,
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                }
            }
        }
        action?.invoke()
    }
}

// 设置卡片容器
@Composable
private fun SettingsCard(title: String, content: @Composable ColumnScope.() -> Unit) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        shape = RoundedCornerShape(16.dp),
        elevation = CardDefaults.cardElevation(4.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
    ) {
        Column(modifier = Modifier.padding(vertical = 8.dp)) {
            Text(
                text = title,
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(16.dp)
            )
            content()
        }
    }
}

// 预览组件
@Preview
@Composable
fun SettingsScreenPreview() {
    SettingsScreen()
}
